package com.hpxx.ylzswl.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.adapter.ImagePickerAdapter;
import com.hpxx.ylzswl.base.BaseActivity;
import com.hpxx.ylzswl.event.OrderIdEvent;
import com.hpxx.ylzswl.event.OrderListEvent;
import com.hpxx.ylzswl.https.HttpAddress;
import com.hpxx.ylzswl.https.RequestParams;
import com.hpxx.ylzswl.utils.FileSizeUtil;
import com.hpxx.ylzswl.views.GlideImageLoader;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.universal.frame.generalutils.CameraUtil;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.SharedPreferencesUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Request;

import static com.activeandroid.Cache.getContext;

/**
 * Created by Administrator on 2017/11/14.
 */

public class RequisitionActivity extends BaseActivity implements View.OnClickListener, ImagePickerAdapter.OnRecyclerViewItemClickListener, ResultCallBack {

    private Button my_com_updata;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ArrayList<ImageItem> images = null;
    private RecyclerView recyclerView;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;
    private ImagePickerAdapter adapter;
    private String orderId;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_requisition);

    }

    @Override
    public void initView() {
        setTitle("上传申请单");
        back();
        orderId = getIntent().getStringExtra("ORDER_ID");
        my_com_updata  = (Button) findViewById(R.id.my_com_updata);
        recyclerView  = (RecyclerView) findViewById(R.id.recyclerView);
        my_com_updata.setOnClickListener(this);
        initImagePicker();
        initWidget(recyclerView);
    }
    private void initImagePicker() {
        int Height = SharedPreferencesUtil.getInt(this,"windowHeight");
        int Width = SharedPreferencesUtil.getInt(this,"windowWidth");

        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(false);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(1080);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(1080);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(512);                          //保存文件的宽度。单位像素
        imagePicker.setOutPutY(512);                          //保存文件的高度。单位像素
    }

    private void initWidget(RecyclerView recyclerView) {
        //  RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.my_com_updata:
                post();
                break;
        default:
            break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(this, ImageGridActivity.class);
                /* 如果需要进入选择的时候显示已经选中的图片，
                 * 详情请查看ImagePickerActivity
                 * */
                //  intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;

            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }
    private void post () {
        if(selImageList.size() <= 0){
            ToastUtil.showToast(this,"请选择图片");
            return;
        }
        my_com_updata.setEnabled(false);
        Map<String,File> fileParam =  new HashMap<String,File>();
        fileParam.clear();

        for(int i = 0;i < selImageList.size();i++){
            String path = selImageList.get(i).path;
            try{
                double filesize = FileSizeUtil.getFileOrFilesSize(path,3);
                Log.i("tag","filesize = " + filesize);
                Bitmap bitmap = CameraUtil.decodeBitmap(path,filesize);
                if(bitmap == null){
                    ToastUtil.showToast(this,"图片上传失败");
                    return;
                }
                File imgFile = CameraUtil.bitmapTofile(bitmap);
                Log.e("lzx", "post: "+FileSizeUtil.getFileSize(imgFile) );
                bitmap.recycle();
                fileParam.put("img"+i,imgFile);

            }catch (Exception e){
                e.printStackTrace();
                ToastUtil.showToast(this,"上传失败：请清理手机内存");
            }
        }
        Log.i("tag","fileParam = " + fileParam.size());
        if(fileParam.size() <= 0){
            ToastUtil.showToast(this,"请上传申请单照片");
            return;

        }

        OKHttpUtils.postUploadFileAsync(this
                , HttpAddress.UPLOAD_APYIMG_URL
                , new RequestParams(this).getUploadApyImgParams(orderId)
                , this,fileParam,"files"
                , true,1);

    }

    @Override
    public void onSuccess(String response, int flag) {
        int status = JsonUtil.getInt(response, "status", 0);
        try {
            switch (flag) {
                case 1:
                    UploadImgDetail(response);
                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getContext(), e);
        }
    }

    private void UploadImgDetail(String response) {
        int status = JsonUtil.getInt(response, "status", 0);
        String msg = JsonUtil.getString(response,"msg","");
        if (status == 1){
            EventBus.getDefault().post(new OrderListEvent());
            EventBus.getDefault().post(new OrderIdEvent(orderId));
            my_com_updata.setEnabled(true);
            finish();
        }else {
            ToastUtil.showToast(getApplicationContext(),msg);
        }
    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {

    }
}
